package com.block.api.controller.expose;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.channel.service.IApkInfoService;
import com.block.channel.service.IChannelInfoService;
import com.block.common.constant.ProductConstant;
import com.block.common.service.IChannelCommonService;
import com.block.common.util.IpUtil;
import com.block.db.entity.ChannelInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("exp")
public class ExposeController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IChannelInfoService channelInfoService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApkInfoService apkInfoService;

    @RequestMapping(value = "/test", method = {RequestMethod.GET})
    public String test(HttpServletRequest request,
                          HttpServletResponse response) throws Exception {
        return "success";
    }

    /**
     * 渠道访问，获取落地页接口
     */
    @RequestMapping(value = "/chl/{channelCode}", method = {RequestMethod.GET})
    public String channelInfo(HttpServletRequest request,
                          HttpServletResponse response,
                          @PathVariable(value = "channelCode", required = false) String channelCode,
                          @RequestParam(value = "u", required = false) String uid,
                          @RequestParam(value = "jcid", required = false) String jcid,
                          @RequestParam(value = "bd_vid", required = false) String bd_vid,
                          @RequestParam(value = "sz_rli", required = false) String sz_rli,
                          @RequestParam(value = "landingid", required = false) String landingid,
                          @RequestParam(value = "bxm_id", required = false) String bxm_id,
                          @RequestParam(value = "ccbid", required = false) String ccbid,
//                          @RequestParam(value = "a_oId", required = false) String a_oId,
//                          @RequestParam(value = "a_oId", required = false) String a_oId,
                              ModelMap modelMap,
                          @RequestParam(value = "a_oId", required = false) String a_oId
    ) throws Exception {

        // 查询渠道信息缓存
        ChannelInfo channelInfo = channelCommonService.getChannelInfoCache(channelCode);
        String result = this.canVisit(request, channelInfo);
        if (StrUtil.isNotEmpty(result)){
            modelMap.put("message", result);
            return "error";
        }

        try {
            String ip = IpUtil.getIp(request);
            // 2.根据渠道信息，获取相应的下载页
            String viewUrl = channelInfoService.channelViewInfo(channelInfo, ip, request);

            if (StrUtil.isEmpty(viewUrl)){
                response.setStatus(404);
                return "";
            }

            if (StrUtil.isNotEmpty(uid)){
                viewUrl = viewUrl + "&u="+uid;
            }

            // 极准
            if (StrUtil.isNotEmpty(jcid)){
                viewUrl = viewUrl + "&jcid="+jcid;
            }

            // 百度
            if (StrUtil.isNotEmpty(jcid)){
                viewUrl = viewUrl + "&bd_vid="+bd_vid;
            }

            // 索知
            if (StrUtil.isNotEmpty(sz_rli)){
                viewUrl = viewUrl + "&sz_rli="+sz_rli;
            }

            // 索知
            if (StrUtil.isNotEmpty(landingid)){
                viewUrl = viewUrl + "&landingid="+landingid;
            }

            // 索知
            if (StrUtil.isNotEmpty(bxm_id)){
                viewUrl = viewUrl + "&bxm_id="+bxm_id;
            }

            // 索知
            if (StrUtil.isNotEmpty(ccbid)){
                viewUrl = viewUrl + "&ccbid="+ccbid;
            }

            // 索知
            if (StrUtil.isNotEmpty(a_oId)){
                viewUrl = viewUrl + "&a_oId="+a_oId;
            }

            // 正常返回页面地址信息
            return "redirect:" + viewUrl;
        }catch (Exception exception){
            exception.printStackTrace();
        }

        modelMap.put("message", "访问出错");
        return "error";
    }

    /**
     * 重定向，返回 apk下载 链接
     * 统计下载数据
     */
    @RequestMapping(value = "/dload/{channelCode}", method = {RequestMethod.GET})
    public String download(HttpServletRequest request,
                          HttpServletResponse response,
                          @PathVariable(value = "channelCode", required = false) String channelCode
    ) throws Exception {

        // 1。查询渠道信息
        if (StrUtil.isEmpty(channelCode)){
            channelCode = ProductConstant.DEFAULT_CHANNEL_CODE;
        }

        String ip = IpUtil.getIp(request);

        // 2.根据渠道信息，获取相应的下载页
        String downloadUrl = apkInfoService.getDownloadUrl(channelCode, ip);

        return "redirect:" + downloadUrl;
    }

    public String canVisit(HttpServletRequest request, ChannelInfo channelInfo){

        try {
            if (ObjectUtil.isEmpty(channelInfo)){
                // 渠道信息为空，不可以通过渠道信息进行访问
                return "渠道信息为空，不可访问";
            }

            if (ObjectUtil.equal(channelInfo.getStatus(), Integer.valueOf(0)) ||
                    ObjectUtil.equal(channelInfo.getDelFlag(), Integer.valueOf(1))){
                // 渠道下架或者删除，不可以进行访问
                return "当前渠道已关闭";
            }

            String userAgentStr = request.getHeader("User-Agent");
            UserAgent userAgent = UserAgentUtil.parse(userAgentStr);

            // 来源屏蔽
            List<String> browserNameList = JSON.parseArray(channelInfo.getNotIncludeSource(), String.class);
            String browserName = userAgent.getBrowser().getName();
            if (CollUtil.isNotEmpty(browserNameList) && browserNameList.contains(browserName)){
                return "当前应用不支持访问";
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "";
    }

    @ResponseBody
    @RequestMapping(value = "/test1/checkUser1", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject checkUser1(HttpServletRequest request,
                                HttpServletResponse response) throws Exception {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
            String ip= ServletUtil.getClientIP(request);
            JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
            String requestNo = jsonObjectParamContent.getString("requestNo");//requestNo
            String appCode = jsonObjectParamContent.getString("appCode");//appCode
            String tranData = jsonObjectParamContent.getString("tranData");//requestNo

            System.out.println("requestNo=============================="+requestNo);
            System.out.println("appCode================================"+appCode);

            String key = "ABVYORIBOKNNEEMTNNWIPCQVGEKIGQQT";
            String s = SecureUtil.aes(key.getBytes()).decryptStr(tranData);
            System.out.println("解密数据=========================="+s);
            JSONObject jsonObject2 = JSONObject.parseObject(s);
            String outOrderNo = jsonObject2.getString("outOrderNo");

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("requestNo",requestNo);
            jsonObject.put("respCode","200");
            jsonObject.put("respMsg","撞库成功");
            JSONObject respData = new JSONObject();
            respData.put("orderNo", UUID.randomUUID().toString());
            respData.put("outOrderNo",outOrderNo);
            respData.put("productId","9999");
            respData.put("productName","测试产品");
            respData.put("companyName","测试机构");
            respData.put("companyLogo","baidu.com");
            respData.put("maxLoanAmount","11111");
            respData.put("maxLoanRate","11");
            respData.put("minLoanRate","1");
            respData.put("businessInfo","信用贷款");
            respData.put("price",8.01);
            JSONArray protocalList = new JSONArray();
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("protocalName","协议名称");
            jsonObject1.put("protocalUrl","www.hang.com");
            protocalList.add(jsonObject1);
            respData.put("protocalList",protocalList);
            jsonObject.put("respData",respData);
            return jsonObject;
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return new JSONObject();
    }

    @ResponseBody
    @RequestMapping(value = "/test1/registerUser1", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject registerUser1(HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {

        Map<String, String[]> parameterMap = request.getParameterMap();
        String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
        String ip= ServletUtil.getClientIP(request);
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        String requestNo = jsonObjectParamContent.getString("requestNo");//requestNo
        String appCode = jsonObjectParamContent.getString("appCode");//appCode
        String tranData = jsonObjectParamContent.getString("tranData");//requestNo

        System.out.println("requestNo=============================="+requestNo);
        System.out.println("appCode================================"+appCode);

        String key = "ABVYORIBOKNNEEMTNNWIPCQVGEKIGQQT";
        String s = SecureUtil.aes(key.getBytes()).decryptStr(tranData);
        System.out.println("解密数据=========================="+s);


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestNo",requestNo);
        jsonObject.put("respCode","200");
        jsonObject.put("respMsg","撞库成功");
        JSONObject respData = new JSONObject();
        respData.put("orderNo",UUID.randomUUID().toString());
        respData.put("message","进件成功");
        respData.put("status","000");
        jsonObject.put("respData",respData);

        return jsonObject;
    }


}
